package com.shopping.huaju.commodity.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping.huaju.commodity.dao.SpuInfoDao;
import com.shopping.huaju.commodity.entity.SkuImagesEntity;
import com.shopping.huaju.commodity.entity.SpuInfoDescEntity;
import com.shopping.huaju.commodity.entity.SpuInfoEntity;
import com.shopping.huaju.commodity.entity.vo.SearchResultVO;
import com.shopping.huaju.commodity.entity.vo.SkuItemSaleAttrVo;
import com.shopping.huaju.commodity.entity.vo.SkuItemVo;
import com.shopping.huaju.commodity.entity.vo.SpuItemAttrGroupVo;
import com.shopping.huaju.commodity.service.*;
import com.shopping.huaju.common.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping.huaju.common.utils.PageUtils;
import com.shopping.huaju.common.utils.Query;

import com.shopping.huaju.commodity.dao.SkuInfoDao;
import com.shopping.huaju.commodity.entity.SkuInfoEntity;

import javax.annotation.Resource;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Resource
    private SpuInfoDao spuInfoDao;
    @Resource
    private ThreadPoolExecutor executor;

    @Resource
    private SkuImagesService skuImagesService;

    @Resource
    private SpuInfoDescService spuInfoDescService;

    @Resource
    private AttrgroupService attrGroupService;

    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuBaseInfos(SkuInfoEntity skuInfoEntity) {
        this.save(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByConditions(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        //如果存在检索条件(id匹配或name模糊查询)则加入到查询条件中
        if(StringUtils.isNotBlank(key)){
            queryWrapper.and(wrapper->{
                wrapper.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        // 如果存在分类查询条件,并且分类id不为零(默认传的是0）则添加到查询条件中
        String catalogId = (String)params.get("catalogId");
        if(StringUtils.isNotBlank(catalogId) && !"0".equals(catalogId)){
            queryWrapper.eq("catalog_id",catalogId);
        }
        //如果存在品牌查询条件，而且品牌id不为0(默认传的是0) 则添加到查询条件中去
        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotBlank(brandId) && !"0".equals(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        //如果携带商品发布价格约束条件，则添加到查询条件中去
       String minPrice = (String) params.get("min");
        if(StringUtils.isNotBlank(minPrice)){
            queryWrapper.ge("price",minPrice);
        }
        String maxPrice = (String) params.get("max");
        if(StringUtils.isNotBlank(maxPrice) && !"0".equals(maxPrice)){
            queryWrapper.le("price",maxPrice);
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
               queryWrapper
        );
        return new PageUtils(page);

    }
    //带条件的分页查询返回用户前台 商品sku 信息列表
    @Override
    public SearchResultVO searchSkuInfosInPage(Map<String, Object> params) {
        //首要条件 商品Spu 必须是在上架的状态
        //获取处于上架状态的
        List<SpuInfoEntity> spuInfoEntities = spuInfoDao.selectList(new QueryWrapper<SpuInfoEntity>().eq("publish_status", 1));
        if (spuInfoEntities == null || spuInfoEntities.isEmpty()){
            SearchResultVO searchResult = new SearchResultVO();
            searchResult.setPageNum(1);
            searchResult.setCommodity(new ArrayList<>());
            searchResult.setTotalPages(1);
            searchResult.setTotal(0l);
            searchResult.setPageNavs(new ArrayList<>());
            searchResult.setKeyword("");
            return searchResult;
        }
        List<Long> availEntitiesId = spuInfoEntities.stream().map(entity -> entity.getId()).collect(Collectors.toList());
        //关键词条件
        String keyword = (String) params.get("keyword");
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("spu_id",availEntitiesId);
        if(StringUtils.isNotBlank(keyword)){
            queryWrapper.like("sku_name",keyword);
        }
        //分类条件
        String catalog3Id = (String)params.get("catalog3Id");
        if(StringUtils.isNotBlank(catalog3Id) && !"0".equals(catalog3Id)){
            queryWrapper.eq("catalog_id",catalog3Id);
        }
        //品牌条件
        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotBlank(brandId)&&!"0".equals(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        IPage<SkuInfoEntity> pageEntity = this.page(new Query<SkuInfoEntity>().getPage(params), queryWrapper);
        PageUtils page = new PageUtils(pageEntity);
        SearchResultVO searchResult = new SearchResultVO();
        searchResult.setCommodity((List<SkuInfoEntity>) page.getList());
        searchResult.setTotal((long)page.getTotalCount());
        searchResult.setPageNum(page.getCurrPage());
        searchResult.setKeyword(keyword == null? "":keyword);
        int totalPage = page.getTotalPage();
        searchResult.setTotalPages(totalPage);
        ArrayList<Integer> navs = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            navs.add(i);
        }
        searchResult.setPageNavs(navs);
        return searchResult;
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return skuInfoEntities;
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1、sku基本信息的获取  pms_sku_info
            SkuInfoEntity info = this.getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        }, executor);


        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //3、获取spu的销售属性组合
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        }, executor);


        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            //4、获取spu的介绍    pms_spu_info_desc
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);
        }, executor);


        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //5、获取spu的规格参数信息
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        }, executor);


        // Long spuId = info.getSpuId();
        // Long catalogId = info.getCatalogId();

        //2、sku的图片信息    pms_sku_images
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> imagesEntities = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(imagesEntities);
        }, executor);

        //CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
        //    //3、远程调用查询当前sku是否参与秒杀优惠活动
        //    R skuSeckilInfo = seckillFeignService.getSkuSeckilInfo(skuId);
        //    if (skuSeckilInfo.getCode() == 0) {
        //        //查询成功
        //        SeckillSkuVo seckilInfoData = skuSeckilInfo.getData("data", new TypeReference<SeckillSkuVo>() {
        //        });
        //        skuItemVo.setSeckillSkuVo(seckilInfoData);
        //
        //        if (seckilInfoData != null) {
        //            long currentTime = System.currentTimeMillis();
        //            if (currentTime > seckilInfoData.getEndTime()) {
        //                skuItemVo.setSeckillSkuVo(null);
        //            }
        //        }
        //    }
        //}, executor);


        //等到所有任务都完成
        CompletableFuture.allOf(saleAttrFuture,descFuture,baseAttrFuture,imageFuture).get();

        return skuItemVo;
    }

}